#pragma once

#include <iostream>
#include <unistd.h>
#include <cstring>
#include <stdarg.h>
#include <time.h>

std::string filename = "log/tcpserver.log";

enum
{
    DEBUG=1,
    INFO,
    WARNING,
    ERROR,
    FATAL
};

std::string toLevelString(int level)
{
    switch (level)
    {
    case DEBUG:
        return "DEBUG";
    case INFO:
        return "INFO";
    case WARNING:
        return "WARNING";
    case ERROR:
        return "ERROR";
    case FATAL:
        return "FATAL";
    default:
        return "Unknow";    
    }
}

std::string getTime()
{
    time_t curr = time(nullptr);
    struct tm* tmp = localtime(&curr);
    char buffer[128];
    snprintf(buffer, sizeof(buffer), "%d-%d-%d %d:%d:%d", tmp->tm_year+1900, tmp->tm_mon+1, tmp->tm_mday,
        tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
    return buffer;
}

void logMessage(int level, const char* format, ...)
{
    char logLeft[1024];
    std::string level_string = toLevelString(level);
    std::string curr_time = getTime();
    snprintf(logLeft, sizeof(logLeft), "[%s] [%s] [%d]", level_string.c_str(), curr_time.c_str(), getpid());

    char logRight[1024];
    va_list p;
    va_start(p, format);
    vsnprintf(logRight, sizeof(logRight), format, p);
    va_end(p);

    FILE* fp = fopen(filename.c_str(), "a");
    if (fp == nullptr)
    {
        return;
    }
    fprintf(fp, "%s%s\n", logLeft, logRight);
    fflush(fp);
    fclose(fp);
}
